package com.alibaba.nacos.core.cluster;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.ConcurrentSkipListMap;

@Component
public class ServerMemberManager
        implements ApplicationListener<WebServerInitializedEvent> {

    private volatile ConcurrentSkipListMap<String, Member> serverMap = new ConcurrentSkipListMap<>();
    private volatile Member self;
    private int port;
    private String ip;
    private String localAddress;

    @Autowired
    private Environment environment;


    @SneakyThrows
    @PostConstruct
    public void init() {
        this.port = Integer.parseInt(environment.getProperty("server.port"));
        this.ip = InetAddress.getLocalHost().getHostAddress();
        this.localAddress = ip + ":" + port;
        Member member = MemberUtil.singleParse(this.ip, this.port);
        member.getExtendInfo().put("version", "2.5.1");
        member.getExtendInfo().put("supportGrayModel", true);
        member.setGrpcReportEnabled(true);
        this.self = member;
        this.serverMap.put(member.getAddress(), member);
    }

    public Member find(String address) {
        return serverMap.get(address);
    }


    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {

    }

    public List<Member> allMembersWithoutSelf() {
        List<Member> members = serverMap.values().stream().toList();
        return members;
    }
}
